import { useState, useEffect, useRef, useMemo } from 'react';
import { Button, Space } from 'antd';
import { Table, MF, Form } from 'com';
import menuStore from 'store/menu';
import { getAttendanceList, getAuditStatus } from 'api/dictionary';
import { ApplyAttendance, SearchMyAttendances } from 'api/teacher_attendance_audit';
import FlowList from './components/FlowList';
import dayjs from 'dayjs';

/**
 * 调课和请假（需要时间）
 */
const dateType = [33, 34];
/**
 * 格式化字符串
 */
const formatString = 'YYYY-MM-DD HH:mm:ss';

export default () => {
    /**
   * 考勤列表
   */
    const [list, setList] = useState([]);
    /**
     * 总条数
     */
    const [total, setTotal] = useState(0);
    /**
     * 考勤类型
     */
    const [attendances, setAttendances] = useState([]);
    /**
     * 要操作的审批流
     */
    const [flow, setFlow] = useState({});
    /**
     * 审批状态
     */
    const [status, setStatus] = useState([]);
    /**
     * 考勤
     */
    const [attendance, setAttendance] = useState({});
    /**
     * loading
     */
    const [loading, setLoading] = useState(false);
    /**
     * 搜索模型
     */
    const [searchModel, setSearchModel] = useState({
        pageNo: 1,
        pageSize: 10,
        status: 0,
        attendance_id: 0
    });
    /**
     * 添加MF引用
     */
    const addMF = useRef();
    /**
     * 列
     */
    const cols = [
        {
            title: '考勤类型',
            dataIndex: 'attendance_name',
            align: "center"
        },
        {
            title: '开始时间',
            dataIndex: 'from_date',
            align: 'center',
            render: text => text && dayjs(text).format(formatString),
        },
        {
            title: '结束时间',
            dataIndex: 'end_date',
            align: 'center',
            render: text => text && dayjs(text).format(formatString),
        },
        {
            title: '我的课程',
            align: 'center',
            render: (text, { ffrom_date, fend_date }) => ffrom_date && `${dayjs(ffrom_date).format(formatString)}至${dayjs(fend_date).format(formatString)}`
        },
        {
            title: '调换课程',
            align: 'center',
            render: (text, { efrom_date, eend_date }) => efrom_date && `${dayjs(efrom_date).format(formatString)}至${dayjs(eend_date).format(formatString)}`
        },
        {
            title: '消息',
            dataIndex: 'message'
        },
        {
            title: '状态',
            dataIndex: 'status_name',
            align: 'center'
        },
        {
            title: '操作',
            align: 'center',
            width: 150,
            render: (text, row) => <Space>
                {menuStore.auth('updateRole') && <Button type="link" size="small" onClick={() => setFlow({ ...row })}>编辑</Button>}
            </Space>
        }
    ]
    /**
     * 添加修改表单配置项
     */
    const options = useMemo(() => ({
        attendance_id: {
            title: '考勤类型',
            required: true,
            tag: 'select',
            attrs: { onChange(value) { setAttendance({ attendance_id: value }) } },
            values: attendances
        },
        ...(dateType.includes(attendance.attendance_id) ? {
            from_date: {
                title: '起止时间',
                tag: 'dateRange',
                showTime: true,
                required: true
            }
        } : attendance.attendance_id === 35 ? {
            from_course_id: {
                title: '我的课程',
                tag: 'css',
                isSelf: true,
                required: true,
            },
            to_course_id: {
                title: '调换的课程',
                tag: 'css',
                isSelf: false,
                required: true
            }
        } : null),
        message: {
            title: '留言',
            tag: 'textArea',
            required: true,
            max: 200,
        }
    }), [attendances, attendance]);
    /**
     * 搜索表单配置项
     */
    const saerchOptions = useMemo(() => ({
        attendance_id: {
            title: '考勤类型',
            tag: 'select',
            style: { width: 130 },
            values: [{ label: '所有', value: 0 }, ...attendances]
        },
        status: {
            title: '审批状态',
            tag: 'select',
            style: { width: 130 },
            values: [{ label: '所有', value: 0 }, ...status]
        },
        search: {
            tag: 'button',
            text: '搜索',
            loading,
            htmlType: 'submit',
            type: 'primary'
        }
    }), [attendances, status, loading]);

    menuStore.auth('roleList') && useEffect(() => {
        (async () => {
            try {
                const list = await getAttendanceList();
                setAttendances(list.map(c => ({ label: c.name, value: c.id })));
            } catch (error) { }
        })();

        (async () => {
            try {
                const list = await getAuditStatus();
                setStatus(list.map(c => ({ label: c.name, value: c.id })));
            } catch (error) { }
        })()
    }, []);

    useEffect(() => {
        (async () => {
            try {
                setLoading(true);
                const { data, total } = await SearchMyAttendances(searchModel);
                setList(data);
                setTotal(total);
            } catch (error) { }
            setLoading(false);
        })()
    }, [searchModel]);

    /**
     * 提交
     * @param {*} values 
     */
    const confirm = async values => {
        try {
            addMF.current.start();
            if (dateType.includes(values.attendance_id)) {
                const [from, end] = values.from_date;
                values.from_date = dayjs(from).format('YYYY-MM-DD HH:mm:ss');
                values.end_date = dayjs(end).format('YYYY-MM-DD HH:mm:ss');
            }
            // await (role.id ? UpdateRole : AddRole)({ id: role.id, ...values });
            await ApplyAttendance(values);
            setSearchModel({ ...searchModel });
            addMF.current.hide();
        } catch (error) { }
        addMF.current.stop();
    }

    return <div>
        <h3>我的考勤</h3>
        <hr />
        <Space size={0}>
            <Form attrs={{ layout: 'inline' }} options={saerchOptions} values={searchModel} onFinish={obj => setSearchModel({ ...searchModel, ...obj, pageNo: 1 })} />
            {menuStore.auth('addRole') && <Button type="primary" onClick={() => addMF.current.show()}>考勤申请</Button>}
        </Space>
        <p></p>
        {menuStore.auth('roleList') && <Table cols={cols} data={list} loading={loading} page={searchModel} total={total} onChange={setSearchModel} />}
        {menuStore.auth('addRole', 'updateRole') && <MF onFinish={confirm} ref={addMF} title="考勤申请" options={options} lw={90} values={attendance} />}
        <FlowList flow={flow} onOK={() => setSearchModel({ ...searchModel })} />
    </div>
}